<template>
    <div class="page-container">
        <div class="in-container search-form-box">
            <AppSearchFormHidden
                class="search-form"
                size="small"
                :label-width="'80'"
                @search="getTableData"
                @reset="reset"
            >
                <template #default>
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="实际开航">
                                <el-date-picker
                                    v-model="etd"
                                    type="daterange"
                                    style="width: 100%;"
                                    value-format="YYYY-MM-DD"
                                    range-separator="~"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    size="small"
                                    :clearable="false"
                                    :unlink-panels="true"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="客户名称">
                                <el-select
                                    v-model="query.CustId"
                                    placeholder="请选择"
                                    style="width: 100%;"
                                    filterable
                                    clearable
                                    remote
                                    :remote-method="getCustomer"
                                    :loading="customerLoading"
                                >
                                    <el-option
                                        v-for="item in customerList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="业务员">
                                <el-select
                                    v-model="query.SalesId"
                                    placeholder="请选择"
                                    style="width: 100%;"
                                    filterable
                                    clearable
                                    remote
                                    :remote-method="getSalesman"
                                    :loading="salesmanLoading"
                                >
                                    <el-option
                                        v-for="item in salesman"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="运输方式">
                                <el-select
                                    v-model="query.Transport"
                                    placeholder="请选择"
                                    style="width: 100%;"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="item in transportationList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="是否退关">
                                <el-select
                                    v-model="query.IsShutout"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 100%;"
                                    clearable
                                >
                                    <el-option
                                        :value="-2"
                                        :label="'全部'"
                                    />
                                    <el-option
                                        :value="0"
                                        :label="'否'"
                                    />
                                    <el-option
                                        :value="1"
                                        :label="'是'"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="订舱单位">
                                <el-select
                                    v-model="query.BookingAgentId"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 100%;"
                                    clearable
                                    remote
                                    :remote-method="getBookParty"
                                    :loading="bookPartLoading"
                                >
                                    <el-option
                                        v-for="item in bookPartyList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    >
                                        <span>{{ item.entCode + ' / ' + item.label }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="业务编号">
                                <el-input
                                    v-model="query.BussinessNo"
                                    clearable
                                    placeholder="请输入"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="提单号">
                                <el-input
                                    v-model="query.BlNo"
                                    clearable
                                    placeholder="请输入"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="客户单号">
                                <el-input
                                    v-model="query.CustDocNo"
                                    clearable
                                    placeholder="请输入"
                                    style="width:100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="船公司">
                                <el-select
                                    v-model="query.ShipCompanyId"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 100%;"
                                    clearable
                                    remote
                                    :remote-method="getShipsCompany"
                                    :loading="shipsCompanyLoading"
                                >
                                    <el-option
                                        v-for="item in shipsCompanyList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    >
                                        <span>{{ item.label + ' / ' + item.entName }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <template #hidden>
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="接单日期">
                                <el-date-picker
                                    v-model="recDate"
                                    type="daterange"
                                    style="width: 100%;"
                                    value-format="YYYY-MM-DD"
                                    range-separator="~"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    size="small"
                                    :clearable="false"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="航线">
                                <el-select
                                    v-model="query.TradelaneId"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 100%;"
                                    clearable
                                    remote
                                    :remote-method="getLineList"
                                    :loading="lineLoading"
                                >
                                    <el-option
                                        v-for="item in lineList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="起运港">
                                <el-select
                                    v-model="query.PolPortId"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 100%;"
                                    clearable
                                    remote
                                    :remote-method="getPortList"
                                    :loading="portLoading"
                                >
                                    <el-option
                                        v-for="item in portList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="目的港">
                                <el-select
                                    v-model="query.DestPortId"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 100%;"
                                    clearable
                                    remote
                                    :remote-method="getPortList"
                                    :loading="portLoading"
                                >
                                    <el-option
                                        v-for="item in portList"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
            </AppSearchFormHidden>
        </div>
        <div class="in-container table-box">
            <div class="btn-box">
                <el-button
                    type="default"
                    icon="RefreshRight"
                    @click="getTableData"
                >
                </el-button>
                <el-button
                    type="primary"
                    @click="exportExcel"
                >导出Execl</el-button>
            </div>
            <AppPageTable
                class="table"
                stripe
                :data="tableData.data"
                :autostyle="'height: calc(100% - 50px) ;'"
                :option="tableData.option"
                :summaryMethod="sumTabel"
                :showSummary="true"
                :sumText="'合计'"
                @change="getTableData()"
            >
                <el-table-column
                    type="selection"
                    width="80"
                    align="center"
                    fixed="left"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="业务编号"
                    prop="doccode"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="提单号"
                    prop="bl_no"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="船名"
                    prop="vessel"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="航次"
                    prop="voyage"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="预计开航日"
                >
                    <template #default="scope">
                        {{ scope.row.etd ? $utils.formatDateTime(scope.row.etd, "YYYY-MM-DD") : "" }}
                    </template>
                </el-table-column>
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="实际开航日"
                >
                    <template #default="scope">
                        {{ scope.row.atd ? $utils.formatDateTime(scope.row.atd, "YYYY-MM-DD") : "" }}
                    </template>
                </el-table-column>
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="船公司"
                    prop="shipcompany_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="订舱代理"
                    prop="booking_agent_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="运输方式"
                    prop="transport"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="起运港"
                    prop="port_departure_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="目的港"
                    prop="port_destination_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="客户"
                    prop="cust_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="业务员"
                    prop="sales_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="操作员"
                    prop="operater_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="订舱员"
                    prop="booking_name"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="件数"
                    prop="digit"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="毛重"
                    prop="gross_weight"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="体积"
                    prop="volume"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="箱型箱量"
                    prop="ctn_digit"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="20'"
                    prop="c20"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="40'"
                    prop="c40"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="40'H"
                    prop="c40h"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="45'"
                    prop="c45"
                />
                <el-table-column
                    width="100px"
                    show-overflow-tooltip
                    align="center"
                    label="TEU"
                    prop="teu"
                />
                <el-table-column
                    width="110px"
                    show-overflow-tooltip
                    align="center"
                    label="折人民币利润"
                    prop="lrsum"
                />
                <el-table-column
                    show-overflow-tooltip
                    align="center"
                    v-for="item in tableData.title"
                    :label="item.currencyName"
                    :key="item.currencyCode"
                    :prop="item.currencyCode"
                >
                    <el-table-column
                        show-overflow-tooltip
                        align="center"
                        v-for="t in item.child"
                        :label="t.title"
                        :key="t.key"
                        :prop="t.key"
                    >
                    </el-table-column>
                </el-table-column>
            </AppPageTable>
        </div>
    </div>
</template>

<script>
import { defineComponent } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import dayjs from "dayjs";
import AppSearchFormHidden from "@/components/AppSearchFormHidden.vue";
import request from "@/public/request";
export default defineComponent({
    components: {
        AppSearchForm,
        AppSearchFormHidden,
        AppPageTable,
    },
    data() {
        return {
            query: {
                StartAtd: dayjs().add(-1, "month").format("YYYY-MM-DD"),//起始实际开航日
                EndAtd: dayjs().format("YYYY-MM-DD"),//截止实际开航日
                StartRecTime: "",//起始接单日
                EndRecTime: "",//结束接单日
                CustId: "",//客户Id
                SalesId: "",//业务员
                Transport: "",//运输方式
                IsShutout: -2,//是否退关 0 否 1 是
                BussinessNo: "",//业务编号
                BlNo: "",//提单号
                CustDocNo: "",//客户单号
                ShipCompanyId: "",//船司Id
                BookingAgentId: "",//订舱单位Id
                DestPortId: "",//目的港
                PolPortId: "",//起运港
                TradelaneId: "",//航线
            },
            tableData: {
                data: [],
                title: [],
                option: useTableOption(),
            },
            // 查询模式
            queryModel: [
                {
                    label: "按客户",
                    value: 1,
                },
                {
                    label: "按船公司",
                    value: 2,
                },
                {
                    label: "按订舱代理",
                    value: 3,
                },
                {
                    label: "按船名航次",
                    value: 4,
                },
            ],
            // 客户名称
            customerList: [],
            customerLoading: false,
            // 船公司
            shipsCompanyList: [],
            shipsCompanyLoading: false,
            // 订舱单位
            bookPartyList: [],
            bookPartLoading: false,
            // 船名
            shipsList: [],
            //运输方法
            transportationList: [
                {
                    label: "铁路",
                    value: "铁路",
                },
                {
                    label: "空运",
                    value: "空运",
                },
                {
                    label: "海运",
                    value: "海运",
                },
                {
                    label: "货车",
                    value: "货车",
                },
            ],
            // 目的港和起运港
            portList: [],
            portLoading: false,
            // 航线
            lineList: [],
            lineLoading: false,
            // 业务员
            salesman: [],
            salesmanLoading: false,
        };
    },
    computed: {
        // 实际开航
        etd: {
            get: function () {
                return [this.query.StartAtd, this.query.EndAtd];
            },
            set: function (val) {
                if (val) {
                    this.query.StartAtd = val[0];
                    this.query.EndAtd = val[1];
                } else {
                    this.query.StartAtd = "";
                    this.query.EndAtd = "";
                };
            },
        },
        // 接单日期
        recDate: {
            get: function () {
                return [this.query.StartRecTime, this.query.EndRecTime];
            },
            set: function (val) {
                if (val) {
                    this.query.StartRecTime = val[0];
                    this.query.EndRecTime = val[1];
                } else {
                    this.query.StartRecTime = "";
                    this.query.EndRecTime = "";
                };
            },
        },
    },
    methods: {
        sumTabel({ columns, data }) {
            let sumText = [];
            columns.forEach((t, index) => {
                if (index === 0) {
                    sumText[index] = "合计";
                    return;
                }
                if (t.label == "应收" || t.label == "应付" || t.label == "利润" || t.label == "折人民币利润") {
                    const values = data.map((item) => Number(item[t.property]));
                    if (!values.every((value) => Number.isNaN(value))) {
                        sumText[index] = `${values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!Number.isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0)}`;
                    } else {
                        sumText[index] = "N/A";
                    }
                } else {
                    sumText[index] = "";
                }
            });
            return sumText;
        },
        reset() {
            this.query = {
                StartAtd: dayjs().add(-1, "month").format("YYYY-MM-DD"),//起始实际开航日
                EndAtd: dayjs().format("YYYY-MM-DD"),//截止实际开航日
                StartRecTime: "",//起始接单日
                EndRecTime: "",//结束接单日
                CustId: "",//客户Id
                SalesId: "",//业务员
                Transport: "",//运输方式
                IsShutout: -2,//是否退关 0 否 1 是
                BussinessNo: "",//业务编号
                BlNo: "",//提单号
                CustDocNo: "",//客户单号
                ShipCompanyId: "",//船司Id
                BookingAgentId: "",//订舱单位Id
                DestPortId: "",//目的港
                PolPortId: "",//起运港
                TradelaneId: "",//航线
            };
            this.tableData.option.page = 1;
            this.tableData.option.pageSize = 10;
            this.getTableData();
        },
        getTableData() {
            this.tableData.option.loading = true;
            let search = {
                current: this.tableData.option.page,
                pageSize: this.tableData.option.pageSize,
                feeParams: []
            };
            let queryKeysLsit = Object.keys(this.query);
            for (const iterator of queryKeysLsit) {
                if (this.query[iterator] !== "" && this.query[iterator] !== -2) {
                    let keyObject = {
                        key: iterator,
                        value: this.query[iterator],
                    };
                    search.feeParams.push(keyObject);
                };
            };
            this.$http
                .post("/api/reportmanage/getProfitDetails", search)
                .then((res) => {
                    this.tableData.data = res.data.item1.content;
                    this.tableData.title = this.changeTableCurreny(res.data.item2);
                    this.tableData.option.total = res.data.item1.totalElements;
                })
                .finally(() => (this.tableData.option.loading = false));
        },
        /**
         * @typedef {Object} MyObject
         * @property {String} key - 键值
         * @property {String} title - 标题
         * @property {Array.<MyObject>} child - 子对象数组
         *
         * 动态渲染表格货币
         * @param {Array<{key:String,title:String}>} data
         * @returns {Array.<MyObject>}
         */
        changeTableCurreny(data) {
            return data.map((t) => {
                t.child = [];
                t.child.push({ key: `ys${t.currencyCode}`, title: "应收" });
                t.child.push({ key: `yf${t.currencyCode}`, title: "应付" });
                t.child.push({ key: `lr${t.currencyCode}`, title: "利润" });
                return t;
            });
        },

        // 下载报表
        async exportExcel() {
            let feeParams = [];
            let queryKeysLsit = Object.keys(this.query);
            for (const iterator of queryKeysLsit) {
                if (this.query[iterator] !== "" && this.query[iterator] !== -2) {
                    let keyObject = {
                        key: iterator,
                        value: this.query[iterator],
                    };
                    feeParams.push(keyObject);
                };
            };
            const res = await request.downloadByPost("/api/reportmanage/downloadDetFile", {
                feeParams: feeParams
            });
            const reg = /(?=filename\*=UTF-8'').*/;
            let filename = reg.exec(res.header["content-disposition"]);
            filename = decodeURI(filename[0].replace(/filename\*=UTF-8''/, ""));
            const url = URL.createObjectURL(res.blob);
            const a = document.createElement("a");
            a.id = "down-" + new Date().getTime();
            a.setAttribute("href", url);
            a.download = filename;
            a.click();
            URL.revokeObjectURL(a.href);
        },

        // 获取客户名称下拉数据
        async getCustomer(val) {
            this.customerLoading = true;
            let res = await this.$http.get("/api/buenterprise/dropdown", {
                Type: "客户",
                KeyWords: val
            });
            res.content.forEach(item => {
                item.label = item.entName;
                item.value = item.id;
            });
            this.customerList = res.content;
            this.customerLoading = false;
        },


        // 获取船公司下拉数据
        async getShipsCompany(val) {
            this.shipsCompanyLoading = true;
            let res = await this.$http.get("/api/buenterprise/dropdown", {
                Type: "船公司",
                KeyWords: val
            });
            res.content.forEach(item => {
                item.label = item.entCode;
                item.value = item.id;
            });
            this.shipsCompanyList = res.content;
            this.shipsCompanyLoading = false;
        },

        // 获取订舱单位下拉数据
        async getBookParty(val) {
            this.bookPartLoading = true;
            let res = await this.$http.get("/api/buenterprise/dropdown", {
                Type: "订舱单位",
                KeyWords: val
            });
            res.content.forEach(item => {
                item.label = item.entName;
                item.value = item.id;
            });
            this.bookPartyList = res.content;
            this.bookPartLoading = false;
        },

        // 目的港和起运港
        async getPortList(val) {
            this.portLoading = true;
            let res = await this.$http.get("/api/base/port/query", {
                current: -1,
                pageSize: 20,
                KeyWords: val
            });
            res.content.forEach(item => {
                item.label = item.portCode + ',' + item.portEnName;
                item.value = item.id;
            });
            this.portList = res.content;
            this.portLoading = false;
        },

        // 航线
        async getLineList(val) {
            this.lineLoading = true;
            let res = await this.$http.get("/api/base/shipline/query", {
                current: -1,
                pageSize: 20,
                KeyWords: val
            });
            res.content.forEach(item => {
                item.label = item.shiplineName;
                item.value = item.id;
            });
            this.lineList = res.content;
            this.lineLoading = false;
        },

        // 获取业务员
        async getSalesman(val) {
            this.salesmanLoading = true;
            let res = await this.$http.get("/api/user/userCashList", {
                keyword: val
            });
            res.forEach(item => {
                item.label = item.realname;
                item.value = item.id;
            });
            this.salesman = res;
            this.salesmanLoading = false;
        },
    },
    mounted() {
        this.getTableData();
    },
});
</script>

<style lang="scss" scoped>
.page-container {
    display: flex;
    flex-direction: column;

    .search-form-box {
        height: auto;
        margin-bottom: 8px;

        :deep(.form .el-form-item) {
            width: 100%;
            margin-right: 0;
        }
    }

    .btn-box {
        margin-bottom: 8px;
    }

    .table-box {
        flex: 1;
    }
}
</style>
